package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.common.constant.SeckillConstant;
import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @create: 2024/9/16
 * @author: gyhe10
 * @description: 秒杀商品定时上架
 *      每天晚上 3 点上架最近三天需要秒杀的商品
 **/

@Slf4j
@Component
public class SeckillSkuScheduled {

    @Resource
    private SeckillService seckillService;
    @Resource
    private RedissonClient redissonClient;

    // @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(cron = "*/5 * * * * ?")// 为了方便测试，改为每分钟执行一次
    public void uploadSeckillSkuLatest3Days() {
        // 因为每天晚上 3 点上架最近三天需要秒杀的商品，会涉及一个秒杀商品重复上架问题，但是无需处理
        // log.info("开始进行秒杀商品上架...");
        // 获取分布式锁
        RLock lock = redissonClient.getLock(SeckillConstant.UPLOAD_LOCK);
        // 加锁
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}
